package controller

import (
	"fmt"
	"mumu_stock_trad/model"
	"net/http"
	"strconv"
	"strings"

	"github.com/gin-gonic/gin"
)

// intersectSlices finds the intersection of all slices in the map.
func intersectSlices(m map[string][]string) []string {
	if len(m) == 0 {
		return []string{}
	}

	// Start with the first slice in the map
	var intersected []string
	firstSlice := m[findFirstKey(m)]

	// Convert the first slice to a map for quick lookup
	firstSliceMap := make(map[string]struct{})
	for _, item := range firstSlice {
		firstSliceMap[item] = struct{}{}
	}

	// Find the intersection with each subsequent slice
	for _, slice := range m {
		tempMap := make(map[string]struct{})
		for _, item := range slice {
			if _, exists := firstSliceMap[item]; exists {
				tempMap[item] = struct{}{}
			}
		}
		firstSliceMap = tempMap
	}

	// Convert the resulting map to a slice
	for item := range firstSliceMap {
		intersected = append(intersected, item)
	}

	return intersected
}

// Helper function to find the first key in the map
func findFirstKey(m map[string][]string) string {
	for k := range m {
		return k
	}
	return ""
}

var (
	SrockFilterCondition = map[string][]string{}
)

type GetDetailParam struct {
	StockCode string `json:"stockCode"`
	Days      int    `json:"days"`
}

type Char struct {
	StockCode     string  `json:"stockCode"`
	StockName     string  `json:"stockName"`
	Date          string  `json:"date"`
	Open          float64 `json:"open"`
	Close         float64 `json:"close"`
	Low           float64 `json:"low"`
	High          float64 `json:"high"`
	TradeMoney    string  `json:"tradeMoney"`
	ClosePrice    float64 `json:"closePrice"`
	ChangePercent float64 `json:"changePercent"`
}

type ParAddFavorite struct {
	StockCode string `json:"stockCode"`
	StockName string `json:"stockName"`
}

func DeleteFavorite(c *gin.Context) {
	var param ParAddFavorite

	// Bind the JSON payload to the PostData struct
	if err := c.BindJSON(&param); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	data := model.StockFavorite{
		StockCode: param.StockCode,
		StockName: param.StockName,
	}

	_ = data.DeleteStockFavorite()

	// 返回成功响应
	c.JSON(http.StatusOK, gin.H{
		"coode":   0,
		"message": "Stock data saved successfully",
		"param":   param,
	})
}

func AddFavorite(c *gin.Context) {
	var param ParAddFavorite

	// Bind the JSON payload to the PostData struct
	if err := c.BindJSON(&param); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	data := model.StockFavorite{
		StockCode: param.StockCode,
		StockName: param.StockName,
	}

	_ = data.StockFavorite()

	// 返回成功响应
	c.JSON(http.StatusOK, gin.H{
		"coode":   0,
		"message": "Stock data saved successfully",
		"param":   param,
	})
}

func formatToWan(num float64) string {
	// 将数字转换为以“万”为单位的字符串
	if num >= 10000 {
		return strconv.FormatFloat(num/10000, 'f', 2, 64) + "万"
	}
	return strconv.FormatFloat(num, 'f', 2, 64)
}

type GetHistoryPar struct {
	StockCode string
	StockName string
}

var chanHistory = make(chan GetHistoryPar)

func init() {
	go func() {
		for value := range chanHistory {
			go GetHistory(value.StockCode, value.StockName)
			fmt.Println("Received:", value)
		}
	}()
}

func GetDetail(c *gin.Context) {
	var param GetDetailParam

	// Bind the JSON payload to the PostData struct
	if err := c.BindJSON(&param); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	page := 1
	pageSize := param.Days

	// list, err := model.GetStockSAListPage(page, pageSize, "date", "desc", param.StockCode)
	// if err != nil {
	// 	// log.Fatal(err)
	// }

	// lie, _ := model.GetStockDetail(page, 1, "date", "asc", param.StockCode)

	// chanHistory <- GetHistoryPar{
	// 	StockCode: lie[0].StockCode,
	// 	StockName: lie[0].StockName,
	// }

	char := []Char{}

	// for _, li := range list {
	// 	char = append(char, Char{
	// 		StockCode:     li.StockCode,
	// 		StockName:     li.StockName,
	// 		Date:          li.Date,
	// 		Open:          li.OpenPrice,
	// 		Close:         li.ClosePrice,
	// 		Low:           li.MinPrice,
	// 		High:          li.MaxPrice,
	// 		TradeMoney:    formatToWan(li.TradeMoney),
	// 		ClosePrice:    li.ClosePrice,
	// 		ChangePercent: li.DiffRate,
	// 	})
	// }

	// if len(list) == 0 {
	list1, err := model.GetStockDetail(page, pageSize, "date", "asc", param.StockCode)
	if err != nil {
		// log.Fatal(err)
	}

	for _, li := range list1 {
		char = append(char, Char{
			StockCode:     li.StockCode,
			StockName:     li.StockName,
			Date:          li.Date,
			Open:          li.TodayOpenPrice,
			Close:         li.CurrentPrice,
			Low:           li.LowestPrice,
			High:          li.HighestPrice,
			TradeMoney:    strconv.FormatFloat(li.TurnoverAmount, 'f', 2, 64),
			ClosePrice:    li.CurrentPrice,
			ChangePercent: li.ChangePercent,
		})
	}
	// }

	// 返回成功响应
	c.JSON(http.StatusOK, gin.H{
		"coode":   0,
		"message": "Stock data saved successfully",
		// "data":    list,
		"char":  char,
		"param": param,
	})
}

type GetListParam struct {
	SearchKey      string      `json:"searchKey"`
	CategoryName   string      `json:"categoryName"`
	OrderBy        string      `json:"orderBy"`
	OrderDirection string      `json:"orderDirection"`
	Condition      []string    `json:"condition"`
	Page           int         `json:"page"`     // 新增字段：当前页
	PageSize       int         `json:"pageSize"` // 新增字段：每页显示的记录数
	Params         interface{} `json:"params"`   // 请求参数
}

// GetStockData 获取股票数据的控制器
func GetList(c *gin.Context) {
	var data interface{}

	// Bind the JSON payload to the PostData struct
	// if err := c.BindJSON(&data); err != nil {
	// 	c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
	// 	return
	// }

	var param GetListParam

	// Bind the JSON payload to the PostData struct
	if err := c.BindJSON(&param); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	page := 1
	pageSize := 400

	if param.OrderBy == "" {
		param.OrderBy = "turnover_rate"
	}

	if param.OrderDirection == "" {
		param.OrderDirection = "desc"
	}

	stockCode := []string{}
	filterCondition := map[string][]string{}

	filter := false

	if param.SearchKey != "" {
		datas, err := model.GetFiter(`SELECT stock_code FROM stock_qt where stock_code like '%` + param.SearchKey + `%' or stock_name like '%` + param.SearchKey + `%' group by stock_code`)
		if err != nil {
			// log.Fatal(err)
		}
		filter = true
		filterCondition["searchKey"] = datas
		if len(datas) == 0 {
			// 返回成功响应
			c.JSON(http.StatusOK, gin.H{
				"coode":           0,
				"message":         "Stock data saved successfully",
				"data":            []model.StockDataQT{},
				"response":        data,
				"param":           param,
				"filterCondition": filterCondition,
				"stockCode":       stockCode,
			})
		}
	}

	if param.CategoryName != "" {
		dataC, err := model.GetFiter(`SELECT code FROM stock_list where category_name like '%` + param.CategoryName + `%'`)
		if err != nil {
			// log.Fatal(err)
		}

		filter = true
		filterCondition["categoryName"] = dataC
		if len(dataC) == 0 {
			// 返回成功响应
			c.JSON(http.StatusOK, gin.H{
				"coode":           0,
				"message":         "Stock data saved successfully",
				"data":            []model.StockDataQT{},
				"response":        data,
				"param":           param,
				"filterCondition": filterCondition,
				"stockCode":       stockCode,
			})
		}
	}

	// 组合各种条件
	if len(param.Condition) > 0 {
		filter = true
		for _, str := range param.Condition {
			parts := strings.Split(str, "-")
			num, err := strconv.Atoi(parts[1])
			if err != nil {
				// log.Fatal(err)
			}
			data := []string{}

			if parts[0] != "favorites" {
				list, exist := SrockFilterCondition[str]
				if exist {
					filterCondition[str] = list
					continue
				}
			}
			switch parts[0] {
			case "favorites":
				data, err = model.GetFiter(`SELECT stock_code FROM stock_favorites`)
			// 涨停
			case "zt":
				query := fmt.Sprintf(
					`SELECT stock_code FROM (  
						SELECT stock_code,count(1) as amount FROM stock_qt 
						WHERE change_percent > 9.5 
						AND date >= (SELECT date FROM (SELECT date FROM stock_qt GROUP BY date ORDER BY date DESC LIMIT %d ) AS subquery ORDER BY date ASC LIMIT 1)
						AND date <= (SELECT date FROM (SELECT date FROM stock_qt GROUP BY date ORDER BY date DESC LIMIT %d ) AS subquery ORDER BY date ASC LIMIT 1)
						GROUP BY stock_code
					) t WHERE amount >= %d`,
					num, 1, num,
				)
				data, err = model.GetFiter(query)
			// 小涨
			case "xz":
				query := fmt.Sprintf(
					`SELECT stock_code FROM (  
						SELECT stock_code,count(1) as amount FROM stock_qt 
						WHERE change_percent > -1 AND change_percent < 6 AND today_open_price < current_price AND today_open_price != 0  
						AND date >= (SELECT date FROM (SELECT date FROM stock_qt GROUP BY date ORDER BY date DESC LIMIT %d ) AS subquery ORDER BY date ASC LIMIT 1)
						AND date <= (SELECT date FROM (SELECT date FROM stock_qt GROUP BY date ORDER BY date DESC LIMIT %d ) AS subquery ORDER BY date ASC LIMIT 1)
						GROUP BY stock_code
					) t WHERE amount >= %d`,
					num, 1, num,
				)
				data, err = model.GetFiter(query)
			// 小跌
			case "xd":
				query := fmt.Sprintf(
					`SELECT stock_code FROM (  
						SELECT stock_code,count(1) as amount FROM stock_qt 
						WHERE change_percent < 0  AND today_open_price > current_price 
						AND date >= (SELECT date FROM (SELECT date FROM stock_qt GROUP BY date ORDER BY date DESC LIMIT %d ) AS subquery ORDER BY date ASC LIMIT 1)
						AND date <= (SELECT date FROM (SELECT date FROM stock_qt GROUP BY date ORDER BY date DESC LIMIT %d ) AS subquery ORDER BY date ASC LIMIT 1)
						GROUP BY stock_code
					) t WHERE amount >= %d`,
					num, 1, num,
				)
				data, err = model.GetFiter(query)
			// 横盘
			case "hp":
				query := fmt.Sprintf(
					`SELECT stock_code FROM (  
						SELECT stock_code,count(1) as amount FROM stock_qt 
						WHERE change_percent > -1  AND change_percent < 1 AND change_percent != 0 AND today_open_price < current_price
						AND date >= (SELECT date FROM (SELECT date FROM stock_qt GROUP BY date ORDER BY date DESC LIMIT %d ) AS subquery ORDER BY date ASC LIMIT 1)
						AND date <= (SELECT date FROM (SELECT date FROM stock_qt GROUP BY date ORDER BY date DESC LIMIT %d ) AS subquery ORDER BY date ASC LIMIT 1)
						GROUP BY stock_code
					) t WHERE amount >= %d`,
					num, 1, num,
				)
				data, err = model.GetFiter(query)
			// 3内涨停
			case "zted":
				query := fmt.Sprintf(
					`SELECT stock_code FROM (  
						SELECT stock_code,count(1) as amount FROM stock_qt 
						WHERE change_percent > 9.5 
						AND date >= (SELECT date FROM (SELECT date FROM stock_qt GROUP BY date ORDER BY date DESC LIMIT %d ) AS subquery ORDER BY date ASC LIMIT 1)
						AND date <= (SELECT date FROM (SELECT date FROM stock_qt GROUP BY date ORDER BY date DESC LIMIT %d ) AS subquery ORDER BY date ASC LIMIT 1)
						GROUP BY stock_code
					) t WHERE amount >= %d`,
					num, 1, 1,
				)
				data, err = model.GetFiter(query)
			// 3内die停
			case "dted":
				query := fmt.Sprintf(
					`SELECT stock_code FROM (  
						SELECT stock_code,count(1) as amount FROM stock_qt 
						WHERE change_percent < -9.5 
						AND date >= (SELECT date FROM (SELECT date FROM stock_qt GROUP BY date ORDER BY date DESC LIMIT %d ) AS subquery ORDER BY date ASC LIMIT 1)
						AND date <= (SELECT date FROM (SELECT date FROM stock_qt GROUP BY date ORDER BY date DESC LIMIT %d ) AS subquery ORDER BY date ASC LIMIT 1)
						GROUP BY stock_code
					) t WHERE amount >= %d`,
					num, 1, 1,
				)
				data, err = model.GetFiter(query)

			case "msz":
				num2, _ := strconv.Atoi(parts[2])
				query := fmt.Sprintf(
					// 涨4跌3
					`SELECT stock_code FROM (  
							SELECT '--' AS '跌3涨4',date,stock_name,stock_code,change_percent,count(1) as amount,sum(change_percent) as total,
							highest_price as '最高价',lowest_price as '最低价',total_market_value as '总市值（亿）',amplitude as '振幅',turnover_rate as '换手率',pb_ratio as '市净率' FROM stock_qt 
							WHERE change_percent < 0 
							AND date >= (SELECT date FROM (SELECT date FROM stock_qt GROUP BY date ORDER BY date DESC LIMIT %d ) AS subquery ORDER BY date ASC LIMIT 1)
							AND date <= (SELECT date FROM (SELECT date FROM stock_qt GROUP BY date ORDER BY date DESC LIMIT 1 ) AS subquery ORDER BY date ASC LIMIT 1)
							AND stock_code in (
									# 连涨几天
									select stock_code from (
											SELECT stock_code,count(1) as amount FROM stock_qt 
											WHERE change_percent > 0 AND change_percent < 5 
											AND date >= (SELECT date FROM (SELECT date FROM stock_qt GROUP BY date ORDER BY date DESC LIMIT %d ) AS subquery ORDER BY date ASC LIMIT 1)
											AND date <= (SELECT date FROM (SELECT date FROM stock_qt GROUP BY date ORDER BY date DESC LIMIT %d ) AS subquery ORDER BY date ASC LIMIT 1) 
											GROUP BY stock_code 
									) t1 WHERE amount >= %d   
							)
							GROUP BY stock_code
					)
					t WHERE amount >= %d ORDER BY total DESC`,
					num2, num2+num, num2+1, num, num2,
				)
				data, err = model.GetFiter(query)
			case "dsz":
				num2, _ := strconv.Atoi(parts[2])
				query := fmt.Sprintf(
					// 跌三涨四
					`SELECT stock_code FROM (  
							SELECT '--' AS '跌3涨4',date,stock_name,stock_code,change_percent,count(1) as amount,sum(change_percent) as total,
							highest_price as '最高价',lowest_price as '最低价',total_market_value as '总市值（亿）',amplitude as '振幅',turnover_rate as '换手率',pb_ratio as '市净率' FROM stock_qt 
							WHERE change_percent > 0 AND change_percent < 5 
							AND date >= (SELECT date FROM (SELECT date FROM stock_qt GROUP BY date ORDER BY date DESC LIMIT %d ) AS subquery ORDER BY date ASC LIMIT 1)
							AND date <= (SELECT date FROM (SELECT date FROM stock_qt GROUP BY date ORDER BY date DESC LIMIT 1 ) AS subquery ORDER BY date ASC LIMIT 1)
							AND stock_code in (
									# 连涨几天
									select stock_code from (
											SELECT stock_code,count(1) as amount FROM stock_qt 
											WHERE change_percent < 0  
											AND date >= (SELECT date FROM (SELECT date FROM stock_qt GROUP BY date ORDER BY date DESC LIMIT %d ) AS subquery ORDER BY date ASC LIMIT 1)
											AND date <= (SELECT date FROM (SELECT date FROM stock_qt GROUP BY date ORDER BY date DESC LIMIT %d ) AS subquery ORDER BY date ASC LIMIT 1) 
											GROUP BY stock_code 
									) t1 WHERE amount >= %d   
							)
							GROUP BY stock_code
					)
					t WHERE amount >= %d ORDER BY total DESC`,
					num2, num2+num, num2+1, num, num2,
				)
				data, err = model.GetFiter(query)
			case "mszdf":
				num2, _ := strconv.Atoi(parts[2])
				query := fmt.Sprintf(
					// 涨4跌3
					`SELECT stock_code FROM (  
							SELECT '--' AS '跌3涨4',date,stock_name,stock_code,change_percent,count(1) as amount,sum(change_percent) as total,
							highest_price as '最高价',lowest_price as '最低价',total_market_value as '总市值（亿）',amplitude as '振幅',turnover_rate as '换手率',pb_ratio as '市净率' FROM stock_qt 
							WHERE change_percent < 0 
							AND date >= (SELECT date FROM (SELECT date FROM stock_qt GROUP BY date ORDER BY date DESC LIMIT %d ) AS subquery ORDER BY date ASC LIMIT 1)
							AND date <= (SELECT date FROM (SELECT date FROM stock_qt GROUP BY date ORDER BY date DESC LIMIT 1 ) AS subquery ORDER BY date ASC LIMIT 1)
							AND stock_code in (
									# 连涨几天
									select stock_code from (
											SELECT stock_code,count(1) as amount FROM stock_qt 
											WHERE change_percent > 0 AND change_percent < 50 
											AND date >= (SELECT date FROM (SELECT date FROM stock_qt GROUP BY date ORDER BY date DESC LIMIT %d ) AS subquery ORDER BY date ASC LIMIT 1)
											AND date <= (SELECT date FROM (SELECT date FROM stock_qt GROUP BY date ORDER BY date DESC LIMIT %d ) AS subquery ORDER BY date ASC LIMIT 1) 
											GROUP BY stock_code 
									) t1 WHERE amount >= %d   
							)
							GROUP BY stock_code
					)
					t WHERE amount >= %d 
					AND stock_code in (
						SELECT stock_code from (
							SELECT t1.date, t1.stock_code, t1.current_price, t2.today_open_price FROM (
									SELECT  date,stock_code,current_price FROM stock_qt 
									WHERE change_percent < 0
									AND date = (SELECT date FROM (SELECT date FROM stock_qt GROUP BY date ORDER BY date DESC LIMIT 1 ) AS subquery ORDER BY date ASC LIMIT 1) 
								) t1
								LEFT JOIN
								(
									SELECT date,stock_code,today_open_price FROM stock_qt 
									WHERE change_percent > 3
									AND date = (SELECT date FROM (SELECT date FROM stock_qt GROUP BY date ORDER BY date DESC LIMIT %d ) AS subquery ORDER BY date ASC LIMIT 1)
								) t2
								ON t1.stock_code = t2.stock_code
						) t WHERE ABS(current_price - today_open_price) <= 0.10 * ABS(current_price) AND current_price < today_open_price 
					)
					ORDER BY total DESC`,
					num2, num2+num, num2+1, num, num2, num2+1,
				)

				data, err = model.GetFiter(query)
			case "tld":
				// 屠龙刀
				// num2, _ := strconv.Atoi(parts[2])
				query := fmt.Sprintf(`SELECT stock_code FROM stock_qt WHERE stock_code in (
						SELECT stock_code FROM (
								SELECT * FROM (  
										SELECT date,stock_name,stock_code,change_percent,count(1) as amount,sum(change_percent) as total,highest_price,
										highest_price as '最高价',lowest_price as '最低价',total_market_value as '总市值（亿）',amplitude as '振幅',turnover_rate as '换手率',pb_ratio as '市净率' FROM stock_qt 
										WHERE change_percent > 9.6 AND change_percent <= 10
										AND date = (SELECT date FROM (SELECT date FROM stock_qt GROUP BY date ORDER BY date DESC LIMIT %d ) AS subquery ORDER BY date ASC LIMIT 1)
										AND stock_code not in (
											SELECT stock_code FROM stock_qt 
											WHERE date = (SELECT date FROM (SELECT date FROM stock_qt GROUP BY date ORDER BY date DESC LIMIT %d ) AS subquery ORDER BY date ASC LIMIT 1)
											AND change_percent > 9.6 AND change_percent <= 10.5
										)
										GROUP BY stock_code
								) t ORDER BY total ASC
						) r
				) 
				AND stock_code not in (
					SELECT stock_code FROM stock_qt 
					WHERE date = (SELECT date FROM (SELECT date FROM stock_qt GROUP BY date ORDER BY date DESC LIMIT  %d) AS subquery ORDER BY date ASC LIMIT 1)
					AND change_percent > 9.6 AND change_percent <= 10.5
				)
				AND date = (SELECT date FROM (SELECT date FROM stock_qt GROUP BY date ORDER BY date DESC LIMIT %d ) AS subquery ORDER BY date ASC LIMIT 1) GROUP BY stock_code ORDER BY change_percent DESC`,
					num+1, num+2, num, num+1)
				data, err = model.GetFiter(query)
			}

			if err != nil {
				// log.Fatal(err)
			}
			filterCondition[str] = data
			SrockFilterCondition[str] = data
		}
	}

	// Compute intersection
	stockCode = intersectSlices(filterCondition)

	list, err := model.GetPaginatedStocks(page, pageSize, param.OrderBy, param.OrderDirection, stockCode, filter)
	if err != nil {
		// log.Fatal(err)
	}

	// 返回成功响应
	c.JSON(http.StatusOK, gin.H{
		"coode":           0,
		"message":         "Stock data saved successfully",
		"data":            list,
		"response":        data,
		"param":           param,
		"filterCondition": filterCondition,
		"stockCode":       stockCode,
	})
}

type GetStockListParam struct {
	Params Param `json:"params"` // 请求参数
}

type Param struct {
	SearchKey      string   `json:"searchKey"`
	CategoryName   string   `json:"categoryName"`
	OrderBy        string   `json:"orderBy"`
	OrderDirection string   `json:"orderDirection"`
	Condition      []string `json:"condition"`
	Page           int      `json:"page"`     // 新增字段：当前页
	PageSize       int      `json:"pageSize"` // 新增字段：每页显示的记录数
}

func GetStockList(c *gin.Context) {
	var data interface{}

	var sparam GetStockListParam

	// Bind the JSON payload to the PostData struct
	if err := c.BindJSON(&sparam); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	param := sparam.Params

	// 如果没有提供分页参数，设置默认值
	if param.Page == 0 {
		param.Page = 1 // 默认页码为1
	}

	if param.PageSize == 0 {
		param.PageSize = 10 // 默认每页显示400条记录
	}

	// 处理排序参数，设置默认排序条件
	if param.OrderBy == "" {
		param.OrderBy = "turnover_rate"
	}

	if param.OrderDirection == "" {
		param.OrderDirection = "desc"
	}

	// 继续你现有的过滤、查询和分页处理逻辑
	// 例如：计算分页的起始索引等
	page := param.Page
	pageSize := param.PageSize
	stockCode := []string{}
	filterCondition := map[string][]string{}

	filter := false

	if param.SearchKey != "" {
		datas, err := model.GetFiter(`SELECT stock_code FROM stock_qt where stock_code like '%` + param.SearchKey + `%' or stock_name like '%` + param.SearchKey + `%' group by stock_code`)
		if err != nil {
			// log.Fatal(err)
		}
		filter = true
		filterCondition["searchKey"] = datas
		if len(datas) == 0 {
			// 返回成功响应
			c.JSON(http.StatusOK, gin.H{
				"coode":           0,
				"message":         "Stock data saved successfully",
				"data":            []model.StockDataQT{},
				"response":        data,
				"param":           param,
				"filterCondition": filterCondition,
				"stockCode":       stockCode,
			})
		}
	}

	if param.CategoryName != "" {
		dataC, err := model.GetFiter(`SELECT code FROM stock_list where category_name like '%` + param.CategoryName + `%'`)
		if err != nil {
			// log.Fatal(err)
		}

		filter = true
		filterCondition["categoryName"] = dataC
		if len(dataC) == 0 {
			// 返回成功响应
			c.JSON(http.StatusOK, gin.H{
				"coode":           0,
				"message":         "Stock data saved successfully",
				"data":            []model.StockDataQT{},
				"response":        data,
				"param":           param,
				"filterCondition": filterCondition,
				"stockCode":       stockCode,
			})
		}
	}

	// 组合各种条件
	if len(param.Condition) > 0 {
		filter = true
		for _, str := range param.Condition {
			parts := strings.Split(str, "-")
			num, err := strconv.Atoi(parts[1])
			if err != nil {
				// log.Fatal(err)
			}
			data := []string{}

			if parts[0] != "favorites" {
				list, exist := SrockFilterCondition[str]
				if exist {
					filterCondition[str] = list
					continue
				}
			}
			switch parts[0] {
			case "favorites":
				data, err = model.GetFiter(`SELECT stock_code FROM stock_favorites`)
			// 涨停
			case "zt":
				query := fmt.Sprintf(
					`SELECT stock_code FROM (  
						SELECT stock_code,count(1) as amount FROM stock_qt 
						WHERE change_percent > 9.5 
						AND date >= (SELECT date FROM (SELECT date FROM stock_qt GROUP BY date ORDER BY date DESC LIMIT %d ) AS subquery ORDER BY date ASC LIMIT 1)
						AND date <= (SELECT date FROM (SELECT date FROM stock_qt GROUP BY date ORDER BY date DESC LIMIT %d ) AS subquery ORDER BY date ASC LIMIT 1)
						GROUP BY stock_code
					) t WHERE amount >= %d`,
					num, 1, num,
				)
				data, err = model.GetFiter(query)
			// 小涨
			case "xz":
				query := fmt.Sprintf(
					`SELECT stock_code FROM (  
						SELECT stock_code,count(1) as amount FROM stock_qt 
						WHERE change_percent > -1 AND change_percent < 6 AND today_open_price < current_price AND today_open_price != 0  
						AND date >= (SELECT date FROM (SELECT date FROM stock_qt GROUP BY date ORDER BY date DESC LIMIT %d ) AS subquery ORDER BY date ASC LIMIT 1)
						AND date <= (SELECT date FROM (SELECT date FROM stock_qt GROUP BY date ORDER BY date DESC LIMIT %d ) AS subquery ORDER BY date ASC LIMIT 1)
						GROUP BY stock_code
					) t WHERE amount >= %d`,
					num, 1, num,
				)
				data, err = model.GetFiter(query)
			// 小跌
			case "xd":
				query := fmt.Sprintf(
					`SELECT stock_code FROM (  
						SELECT stock_code,count(1) as amount FROM stock_qt 
						WHERE change_percent < 0  AND today_open_price > current_price 
						AND date >= (SELECT date FROM (SELECT date FROM stock_qt GROUP BY date ORDER BY date DESC LIMIT %d ) AS subquery ORDER BY date ASC LIMIT 1)
						AND date <= (SELECT date FROM (SELECT date FROM stock_qt GROUP BY date ORDER BY date DESC LIMIT %d ) AS subquery ORDER BY date ASC LIMIT 1)
						GROUP BY stock_code
					) t WHERE amount >= %d`,
					num, 1, num,
				)
				data, err = model.GetFiter(query)
			// 横盘
			case "hp":
				query := fmt.Sprintf(
					`SELECT stock_code FROM (  
						SELECT stock_code,count(1) as amount FROM stock_qt 
						WHERE change_percent > -1  AND change_percent < 1 AND change_percent != 0 AND today_open_price < current_price
						AND date >= (SELECT date FROM (SELECT date FROM stock_qt GROUP BY date ORDER BY date DESC LIMIT %d ) AS subquery ORDER BY date ASC LIMIT 1)
						AND date <= (SELECT date FROM (SELECT date FROM stock_qt GROUP BY date ORDER BY date DESC LIMIT %d ) AS subquery ORDER BY date ASC LIMIT 1)
						GROUP BY stock_code
					) t WHERE amount >= %d`,
					num, 1, num,
				)
				data, err = model.GetFiter(query)
			// 3内涨停
			case "zted":
				query := fmt.Sprintf(
					`SELECT stock_code FROM (  
						SELECT stock_code,count(1) as amount FROM stock_qt 
						WHERE change_percent > 9.5 
						AND date >= (SELECT date FROM (SELECT date FROM stock_qt GROUP BY date ORDER BY date DESC LIMIT %d ) AS subquery ORDER BY date ASC LIMIT 1)
						AND date <= (SELECT date FROM (SELECT date FROM stock_qt GROUP BY date ORDER BY date DESC LIMIT %d ) AS subquery ORDER BY date ASC LIMIT 1)
						GROUP BY stock_code
					) t WHERE amount >= %d`,
					num, 1, 1,
				)
				data, err = model.GetFiter(query)
			// 3内die停
			case "dted":
				query := fmt.Sprintf(
					`SELECT stock_code FROM (  
						SELECT stock_code,count(1) as amount FROM stock_qt 
						WHERE change_percent < -9.5 
						AND date >= (SELECT date FROM (SELECT date FROM stock_qt GROUP BY date ORDER BY date DESC LIMIT %d ) AS subquery ORDER BY date ASC LIMIT 1)
						AND date <= (SELECT date FROM (SELECT date FROM stock_qt GROUP BY date ORDER BY date DESC LIMIT %d ) AS subquery ORDER BY date ASC LIMIT 1)
						GROUP BY stock_code
					) t WHERE amount >= %d`,
					num, 1, 1,
				)
				data, err = model.GetFiter(query)

			case "msz":
				num2, _ := strconv.Atoi(parts[2])
				query := fmt.Sprintf(
					// 涨4跌3
					`SELECT stock_code FROM (  
							SELECT '--' AS '跌3涨4',date,stock_name,stock_code,change_percent,count(1) as amount,sum(change_percent) as total,
							highest_price as '最高价',lowest_price as '最低价',total_market_value as '总市值（亿）',amplitude as '振幅',turnover_rate as '换手率',pb_ratio as '市净率' FROM stock_qt 
							WHERE change_percent < 0 
							AND date >= (SELECT date FROM (SELECT date FROM stock_qt GROUP BY date ORDER BY date DESC LIMIT %d ) AS subquery ORDER BY date ASC LIMIT 1)
							AND date <= (SELECT date FROM (SELECT date FROM stock_qt GROUP BY date ORDER BY date DESC LIMIT 1 ) AS subquery ORDER BY date ASC LIMIT 1)
							AND stock_code in (
									# 连涨几天
									select stock_code from (
											SELECT stock_code,count(1) as amount FROM stock_qt 
											WHERE change_percent > 0 AND change_percent < 5 
											AND date >= (SELECT date FROM (SELECT date FROM stock_qt GROUP BY date ORDER BY date DESC LIMIT %d ) AS subquery ORDER BY date ASC LIMIT 1)
											AND date <= (SELECT date FROM (SELECT date FROM stock_qt GROUP BY date ORDER BY date DESC LIMIT %d ) AS subquery ORDER BY date ASC LIMIT 1) 
											GROUP BY stock_code 
									) t1 WHERE amount >= %d   
							)
							GROUP BY stock_code
					)
					t WHERE amount >= %d ORDER BY total DESC`,
					num2, num2+num, num2+1, num, num2,
				)
				data, err = model.GetFiter(query)
			case "dsz":
				num2, _ := strconv.Atoi(parts[2])
				query := fmt.Sprintf(
					// 跌三涨四
					`SELECT stock_code FROM (  
							SELECT '--' AS '跌3涨4',date,stock_name,stock_code,change_percent,count(1) as amount,sum(change_percent) as total,
							highest_price as '最高价',lowest_price as '最低价',total_market_value as '总市值（亿）',amplitude as '振幅',turnover_rate as '换手率',pb_ratio as '市净率' FROM stock_qt 
							WHERE change_percent > 0 AND change_percent < 5 
							AND date >= (SELECT date FROM (SELECT date FROM stock_qt GROUP BY date ORDER BY date DESC LIMIT %d ) AS subquery ORDER BY date ASC LIMIT 1)
							AND date <= (SELECT date FROM (SELECT date FROM stock_qt GROUP BY date ORDER BY date DESC LIMIT 1 ) AS subquery ORDER BY date ASC LIMIT 1)
							AND stock_code in (
									# 连涨几天
									select stock_code from (
											SELECT stock_code,count(1) as amount FROM stock_qt 
											WHERE change_percent < 0  
											AND date >= (SELECT date FROM (SELECT date FROM stock_qt GROUP BY date ORDER BY date DESC LIMIT %d ) AS subquery ORDER BY date ASC LIMIT 1)
											AND date <= (SELECT date FROM (SELECT date FROM stock_qt GROUP BY date ORDER BY date DESC LIMIT %d ) AS subquery ORDER BY date ASC LIMIT 1) 
											GROUP BY stock_code 
									) t1 WHERE amount >= %d   
							)
							GROUP BY stock_code
					)
					t WHERE amount >= %d ORDER BY total DESC`,
					num2, num2+num, num2+1, num, num2,
				)
				data, err = model.GetFiter(query)
			case "mszdf":
				num2, _ := strconv.Atoi(parts[2])
				query := fmt.Sprintf(
					// 涨4跌3
					`SELECT stock_code FROM (  
							SELECT '--' AS '跌3涨4',date,stock_name,stock_code,change_percent,count(1) as amount,sum(change_percent) as total,
							highest_price as '最高价',lowest_price as '最低价',total_market_value as '总市值（亿）',amplitude as '振幅',turnover_rate as '换手率',pb_ratio as '市净率' FROM stock_qt 
							WHERE change_percent < 0 
							AND date >= (SELECT date FROM (SELECT date FROM stock_qt GROUP BY date ORDER BY date DESC LIMIT %d ) AS subquery ORDER BY date ASC LIMIT 1)
							AND date <= (SELECT date FROM (SELECT date FROM stock_qt GROUP BY date ORDER BY date DESC LIMIT 1 ) AS subquery ORDER BY date ASC LIMIT 1)
							AND stock_code in (
									# 连涨几天
									select stock_code from (
											SELECT stock_code,count(1) as amount FROM stock_qt 
											WHERE change_percent > 0 AND change_percent < 50 
											AND date >= (SELECT date FROM (SELECT date FROM stock_qt GROUP BY date ORDER BY date DESC LIMIT %d ) AS subquery ORDER BY date ASC LIMIT 1)
											AND date <= (SELECT date FROM (SELECT date FROM stock_qt GROUP BY date ORDER BY date DESC LIMIT %d ) AS subquery ORDER BY date ASC LIMIT 1) 
											GROUP BY stock_code 
									) t1 WHERE amount >= %d   
							)
							GROUP BY stock_code
					)
					t WHERE amount >= %d 
					AND stock_code in (
						SELECT stock_code from (
							SELECT t1.date, t1.stock_code, t1.current_price, t2.today_open_price FROM (
									SELECT  date,stock_code,current_price FROM stock_qt 
									WHERE change_percent < 0
									AND date = (SELECT date FROM (SELECT date FROM stock_qt GROUP BY date ORDER BY date DESC LIMIT 1 ) AS subquery ORDER BY date ASC LIMIT 1) 
								) t1
								LEFT JOIN
								(
									SELECT date,stock_code,today_open_price FROM stock_qt 
									WHERE change_percent > 3
									AND date = (SELECT date FROM (SELECT date FROM stock_qt GROUP BY date ORDER BY date DESC LIMIT %d ) AS subquery ORDER BY date ASC LIMIT 1)
								) t2
								ON t1.stock_code = t2.stock_code
						) t WHERE ABS(current_price - today_open_price) <= 0.10 * ABS(current_price) AND current_price < today_open_price 
					)
					ORDER BY total DESC`,
					num2, num2+num, num2+1, num, num2, num2+1,
				)

				data, err = model.GetFiter(query)
			case "tld":
				// 屠龙刀
				// num2, _ := strconv.Atoi(parts[2])
				query := fmt.Sprintf(`SELECT stock_code FROM stock_qt WHERE stock_code in (
						SELECT stock_code FROM (
								SELECT * FROM (  
										SELECT date,stock_name,stock_code,change_percent,count(1) as amount,sum(change_percent) as total,highest_price,
										highest_price as '最高价',lowest_price as '最低价',total_market_value as '总市值（亿）',amplitude as '振幅',turnover_rate as '换手率',pb_ratio as '市净率' FROM stock_qt 
										WHERE change_percent > 9.6 AND change_percent <= 10
										AND date = (SELECT date FROM (SELECT date FROM stock_qt GROUP BY date ORDER BY date DESC LIMIT %d ) AS subquery ORDER BY date ASC LIMIT 1)
										AND stock_code not in (
											SELECT stock_code FROM stock_qt 
											WHERE date = (SELECT date FROM (SELECT date FROM stock_qt GROUP BY date ORDER BY date DESC LIMIT %d ) AS subquery ORDER BY date ASC LIMIT 1)
											AND change_percent > 9.6 AND change_percent <= 10.5
										)
										GROUP BY stock_code
								) t ORDER BY total ASC
						) r
				) 
				AND stock_code not in (
					SELECT stock_code FROM stock_qt 
					WHERE date = (SELECT date FROM (SELECT date FROM stock_qt GROUP BY date ORDER BY date DESC LIMIT  %d) AS subquery ORDER BY date ASC LIMIT 1)
					AND change_percent > 9.6 AND change_percent <= 10.5
				)
				AND date = (SELECT date FROM (SELECT date FROM stock_qt GROUP BY date ORDER BY date DESC LIMIT %d ) AS subquery ORDER BY date ASC LIMIT 1) GROUP BY stock_code ORDER BY change_percent DESC`,
					num+1, num+2, num, num+1)
				data, err = model.GetFiter(query)
			}

			if err != nil {
				// log.Fatal(err)
			}
			filterCondition[str] = data
			SrockFilterCondition[str] = data
		}
	}

	// Compute intersection
	stockCode = intersectSlices(filterCondition)

	list, err := model.GetPaginatedStocks(page, pageSize, param.OrderBy, param.OrderDirection, stockCode, filter)
	if err != nil {
		// log.Fatal(err)
	}

	// 返回统一格式响应
	response := NewResponse(Success, gin.H{
		"list":            list,
		"page":            page,
		"total":           10000,
		"pageSize":        pageSize,
		"param":           param,
		"filterCondition": filterCondition,
	})

	// 返回JSON响应
	c.JSON(http.StatusOK, response)
}
